from Models import *
from Global import *
from ..Widgets.mImageWindow import mImageWindow

class MainWindowClass(QWidget):
    def __init__(self, parent=None):
        super(MainWindowClass, self).__init__(parent)
        self.SetUi()
    
    def SetUi(self):
        """设置主窗口界面"""
        self.setWindowTitle("MainWindow")
        self.setWindowIcon(QIcon("resources/icons/MainIcon.png"))
        self.setLayout(QVBoxLayout())
        self.setGeometry(100,100,800,800)
        
        
        p = QPushButton(self)
        p.clicked.connect(lambda : self.__open_child_window(mImageWindow))
        












    # 私有方法
    def __open_child_window(self, window_class):
        """打开或激活指定类型的子窗口。
        
        如果尚未创建该类型窗口，则新建；若已存在但不可见，则将其恢复正常显示并前置。
        同时会暂时隐藏主窗口。

        Args:
            window_class (type): 要打开的子窗口类
        """
        class_name = window_class.__name__
        
        print("="*50)
        print(f"[{time.ctime()}] 开始打开{class_name}窗口")
        print(f"当前子窗口列表:")
        for index,child in enumerate(self.children()):
            print(f"\t\t index: {index}, child: {child} objectName: {child.objectName()} , className: {child.__class__.__name__}")
        print("="*50)
        
        
        child_window = self.__find_child_window(window_class)
        if not child_window:
            try:
                child_window = window_class(parent=self)
                child_window.setWindowFlags(
                    Qt.Window | 
                    Qt.WindowTitleHint | 
                    Qt.WindowCloseButtonHint |
                    Qt.WindowStaysOnTopHint
                )
                child_window.setAttribute(Qt.WA_DeleteOnClose, False)
                print(f"[{datetime.datetime.now()}] {class_name}窗口显示成功!")
            except Exception as e:
                print(f"[{datetime.datetime.now()}] 创建{class_name}失败: {str(e)}")
                return
        
        try:
            child_window.showNormal()
            child_window.raise_()
            child_window.activateWindow()
            child_window.setFocus()
            child_window.repaint()
            QApplication.processEvents()
            
            print(f"[{datetime.datetime.now()}] {class_name}已强制显示")
            self.hide()
        except Exception as e:
            print(f"[{datetime.datetime.now()}] 显示{class_name}出错: {str(e)}")
            self.show()

    def __find_child_window(self, window_class):
        """查找是否存在有效的指定类型子窗口实例。
        
        Args:
            window_class (type): 子窗口类
            
        Returns:
            QWidget or None: 若存在有效窗口则返回其实例，否则返回None
        """
        class_name = window_class.__name__
        # 通过父窗口查找子控件的方式替换原有的字典查找方式
        child_window = self.findChild(window_class)
        if child_window and child_window.isWidgetType():
            print(f"[{datetime.datetime.now()}] 【{class_name}】类窗口已找到有效实例!无需重复创建!")
            return child_window
        else:
            print(f"[{datetime.datetime.now()}] 【{class_name}】类窗口未找到有效实例!")
            return None